package com.ktgj.flight.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.FlightConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.AssistProductEnum;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.SnowFlake;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.file.api.RemoteFilesService;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.AirReIssuePriceRequest;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.ReIssuePriceResponse;
import com.ktgj.flight.common.linkstar.domain.searchFlight.one.FlightTransfer;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.InterfaceEntity.ChangeSegementInfo;
import com.ktgj.flight.domain.InterfaceEntity.MoOrderChangeRequest;
import com.ktgj.flight.domain.InterfaceEntity.MoOrderChangeResponse;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.mapper.*;
import com.ktgj.flight.service.*;
import com.ktgj.flight.vo.CabinInfoVo;
import com.ktgj.flight.vo.FlightOrderInfoVo;
import com.ktgj.flight.vo.FlightVo;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.PayTypeApi;
import com.ktgj.pay.api.domain.UnionPayQRCodeResponseApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 机票预订_机票订单基本信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-10-26
 */
@Service
public class FlightOrderInfoServiceImpl implements IFlightOrderInfoService 
{
    @Autowired
    private FlightOrderInfoMapper flightOrderInfoMapper;
    @Autowired
    private FlightOrderInfoTicketsMapper flightOrderInfoTicketsMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemotePayService payService;
    @Autowired
    private FlightRevisecabinpriceMapper revisecabinpriceMapper;
    @Autowired
    private FlightAdjustPassengerMapper passengerMapper;
    @Autowired
    private IFlightOrderAddressPostService addressPostService;
    @Autowired
    private IFlightService flightService;
    @Autowired
    private IAirlinerService airlinerService;
    @Autowired
    private IFlightOrderInfoTicketsService orderInfoTicketsService;
    @Autowired
    private IFlightOutticketLogService flightOutticketLogService;
    @Autowired
    private IFlightOrderChangeTicketsService changeTicketsService;
    @Autowired
    private FlightOrderChangeMapper flightOrderChangeMapper;
    @Autowired
    private FlightOrderChangeTicketsMapper flightOrderChangeTicketsMapper;
    @Autowired
    private RemoteFilesService filesService;
    @Autowired
    private FlightOrderChangeTicketsMapper changeTicketsMapper;
    @Autowired
    private IAirportService airportService;
    @Autowired
    private IFlightOrderAssistService flightOrderAssistService;
    @Autowired
    private IFlightOrderInfoTicketsService flightOrderInfoTicketsService;
    @Autowired
    private FlightDeliverAssignMapper flightDeliverAssignMapper;
    @Autowired
    private AirlinerMapper airlinerMapper;
    @Autowired
    private FlightOrderIternaryMapper flightOrderIternaryMapper;
    @Resource
    private FlightOrderAssistMapper flightOrderAssistMapper;


    /**
     * 查询机票预订_机票订单基本信息
     * 
     * @param orderId 机票预订_机票订单基本信息ID
     * @return 机票预订_机票订单基本信息
     */
    @Override
    public FlightOrderInfo selectFlightOrderInfoById(Long orderId)
    {
        return flightOrderInfoMapper.selectFlightOrderInfoById(orderId);
    }

    /**
     * 查询机票预订_机票订单基本信息列表
     * 
     * @param flightOrderInfo 机票预订_机票订单基本信息
     * @return 机票预订_机票订单基本信息
     */
    @Override
    public List<FlightOrderInfo> selectFlightOrderInfoList(FlightOrderInfo flightOrderInfo)
    {
        return flightOrderInfoMapper.selectFlightOrderInfoList(flightOrderInfo);
    }

    /**
     * 新增机票预订_机票订单基本信息
     * 
     * @param flightOrderInfo 机票预订_机票订单基本信息
     * @return 结果
     */
    @Override
    public int insertFlightOrderInfo(FlightOrderInfo flightOrderInfo)
    {
        if (StringHelper.isNullOrEmpty(flightOrderInfo.getContactPhone()))
        {
            return 0;
        }
        Customer customer = remoteCustomerService.getCustomerByMobile(flightOrderInfo.getContactPhone());
        if (customer != null)
        {
            flightOrderInfo.setCustomerId(customer.getCustomerId());
        }
        flightOrderInfo.setCreateTime(DateUtils.getNowDate());
        SnowFlake snowFlake = new SnowFlake(10, 10);
        flightOrderInfo.setOrderId(snowFlake.nextId());
        int rows = 0;
        flightOrderInfo.setSourceTypeId("Other");
        rows = flightOrderInfoMapper.insertFlightOrderInfo(flightOrderInfo);
        if (rows > 0)
        {
            for (FlightOrderInfoTickets flightOrderInfoTickets : flightOrderInfo.getInfoTickets())
            {
                flightOrderInfoTickets.setOrderId(flightOrderInfo.getOrderId());
                flightOrderInfoTicketsMapper.insertFlightOrderInfoTickets(flightOrderInfoTickets);
            }
        }
        return rows;
    }

    @Override
    public int insertFlightOrderInfoDatabase(FlightOrderInfo flightOrderInfo) {
        flightOrderInfo.setCreateTime(DateUtils.getNowDate());
        return flightOrderInfoMapper.insertFlightOrderInfo(flightOrderInfo);
    }

    /**
     * 修改机票预订_机票订单基本信息
     * 
     * @param flightOrderInfo 机票预订_机票订单基本信息
     * @return 结果
     */
    @Override
    public int updateFlightOrderInfo(FlightOrderInfo flightOrderInfo)
    {
        return flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
    }

    /**
     * 批量删除机票预订_机票订单基本信息
     * 
     * @param orderIds 需要删除的机票预订_机票订单基本信息ID
     * @return 结果
     */
    @Override
    public int deleteFlightOrderInfoByIds(Long[] orderIds)
    {
        return flightOrderInfoMapper.deleteFlightOrderInfoByIds(orderIds);
    }

    /**
     * 删除机票预订_机票订单基本信息信息
     * 
     * @param orderId 机票预订_机票订单基本信息ID
     * @return 结果
     */
    @Override
    public int deleteFlightOrderInfoById(Long orderId)
    {
        return flightOrderInfoMapper.deleteFlightOrderInfoById(orderId);
    }

    /**
     * 我的-订单列表（机票）
     * */
    @Override
    public List<AirTicketsVo> selectAirTicketsVo(Long customerId) {
        List<FlightOrderInfo> flightOrderInfoList=flightOrderInfoMapper.selectFlightOrderInfoByCustomerId(customerId);
        List<FlightOrderInfoTickets> flightOrderInfoTicketsList=flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByCustomerId(customerId);

        List<AirTicketsVo> airTicketsVoList=new ArrayList<>();
        List<AirTicketsVo> airTicketsVoList1=new ArrayList<>();
        //遍历flightOrderInfoList
        for (FlightOrderInfo flightOrderInfo:flightOrderInfoList){
            if (flightOrderInfo != null){
                AirTicketsVo airTicketsVo=new AirTicketsVo();
                airTicketsVo.setPnrstatus(flightOrderInfo.getPnrstatus());
                airTicketsVo.setPayAmount(flightOrderInfo.getPayAmount());
                airTicketsVo.setIssueTime(flightOrderInfo.getIssueTime());
                airTicketsVoList.add(airTicketsVo);
            }
            else {
                airTicketsVoList.add(null);
            }
        }
        //遍历flightOrderInfoTicketsList
        for (FlightOrderInfoTickets flightOrderInfoTickets:flightOrderInfoTicketsList){
            AirTicketsVo airTicketsVo=new AirTicketsVo();
            airTicketsVo.setDeparture(flightOrderInfoTickets.getDeparture());
            airTicketsVo.setArrival(flightOrderInfoTickets.getArrival());
            //航班=航空公司+航班号
            airTicketsVo.setFlightJourney(flightOrderInfoTickets.getAirliner()+flightOrderInfoTickets.getFlight());

            //获取出发时间（年、月、日、时、分）
            Calendar departureTime = Calendar.getInstance();
            departureTime.setTime(flightOrderInfoTickets.getDepartureTime());
            int departureYear = departureTime.get(Calendar.YEAR);
            int departureMonth = departureTime.get(Calendar.MONTH);
            int departureDay = departureTime.get(Calendar.DAY_OF_MONTH);
            int departureHourOfDay = departureTime.get(Calendar.HOUR_OF_DAY);
            int departureMinute = departureTime.get(Calendar.MINUTE);

            //获取到达时间（年、月、日、时、分）
            Calendar arrivalTime = Calendar.getInstance();
            arrivalTime.setTime(flightOrderInfoTickets.getArrivalTime());
            int arrivalYear = arrivalTime.get(Calendar.YEAR);
            int arrivalMonth = arrivalTime.get(Calendar.MONTH);
            int arrivalDay = arrivalTime.get(Calendar.DAY_OF_MONTH);
            int arrivalHourOfDay = arrivalTime.get(Calendar.HOUR_OF_DAY);
            int arrivalMinute = arrivalTime.get(Calendar.MINUTE);

            String strDepartureHourOfDay=String.valueOf(departureHourOfDay);
            String strDepartureMinute=String.valueOf(departureMinute);
            String strArrivalHourOfDay=String.valueOf(arrivalHourOfDay);
            String strArrivalMinute=String.valueOf(arrivalMinute);

            //出发时间（时）的值小于10，则拼接‘0’-》”06“
            if (departureHourOfDay<10){
                strDepartureHourOfDay="0"+strDepartureHourOfDay;
            }
            //出发时间（分）的值小于10，则拼接‘0’-》”06“
            if (departureMinute<10){
                strDepartureMinute="0"+strDepartureMinute;
            }
            //到达时间（时）的值小于10，则拼接‘0’-》”06“
            if (arrivalHourOfDay<10){
                strArrivalHourOfDay="0"+strArrivalHourOfDay;
            }
            //到达时间（分）的值小于10，则拼接‘0’-》”06“
            if (arrivalMinute<10){
                strArrivalMinute="0"+strArrivalMinute;
            }

            List<String> strList=conversion((departureMonth+1), departureDay, (arrivalMonth+1), arrivalDay);

            //出发时间与到达时间为同一天-》06-11 14:00 至 17:35
            if (departureYear==arrivalYear && departureMonth==arrivalMonth && departureDay==arrivalDay){
                airTicketsVo.setTime(strList.get(0)+"-"+strList.get(1)+" "+strDepartureHourOfDay+":"+strDepartureMinute+
                        " 至 "+strArrivalHourOfDay+":"+strArrivalMinute);
            }
            else {//出发时间与到达时间不为同一天-》06-11 14:00 至 06-12 17:35
                airTicketsVo.setTime(strList.get(0)+"-"+strList.get(1)+" "+strDepartureHourOfDay+":"+strDepartureMinute+
                        " 至 "+strList.get(2)+"-"+strList.get(3)+" "+strArrivalHourOfDay+":"+strArrivalMinute);
            }
            airTicketsVoList1.add(airTicketsVo);
        }

        for (int i=0;i<airTicketsVoList1.size();i++){
            airTicketsVoList.get(i).setDeparture(airTicketsVoList1.get(i).getDeparture());
            airTicketsVoList.get(i).setArrival(airTicketsVoList1.get(i).getArrival());
            airTicketsVoList.get(i).setFlightJourney(airTicketsVoList1.get(i).getFlightJourney());
            airTicketsVoList.get(i).setTime(airTicketsVoList1.get(i).getTime());
        }

        return airTicketsVoList;
    }

    /**
     * 我的-订单列表（机票-详细信息）
     * */
    @Override
    public FlightOrderInfoVo selectFlightOrderInfoByOrderId(Long orderId, Long customerId) {
        FlightOrderInfoVo flightOrderInfoVo=flightOrderInfoTicketsMapper.selectFlightOrderInfoByOrderId(orderId, customerId);

        Calendar departureTime = Calendar.getInstance();
        departureTime.setTime(flightOrderInfoVo.getDepartureTime());
        int departureYear = departureTime.get(Calendar.YEAR);
        int departureMonth = departureTime.get(Calendar.MONTH);
        int departureDay = departureTime.get(Calendar.DAY_OF_MONTH);
        int departureTimeHourOfDay = departureTime.get(Calendar.HOUR_OF_DAY);
        int departureTimeMinute = departureTime.get(Calendar.MINUTE);

        Calendar arrivalTime = Calendar.getInstance();
        arrivalTime.setTime(flightOrderInfoVo.getArrivalTime());
        int arrivalHourOfDay = arrivalTime.get(Calendar.HOUR_OF_DAY);
        int arrivalMinute = arrivalTime.get(Calendar.MINUTE);

        List<String> stringList=conversion(departureMonth, departureDay, 0, 0);

        String str=flightOrderInfoVo.getAirliner()+flightOrderInfoVo.getFlight()+"·"+departureYear+"-"+stringList.get(0)+"-"+stringList.get(1);
        flightOrderInfoVo.setFlightInformation(str);

        String strDepartureHourOfDay=String.valueOf(departureTimeHourOfDay);
        String strDepartureMinute=String.valueOf(departureTimeMinute);
        String strArrivalHourOfDay=String.valueOf(arrivalHourOfDay);
        String strArrivalMinute=String.valueOf(arrivalMinute);

        //出发时间（时）的值小于10，则拼接‘0’-》”06“
        if (departureTimeHourOfDay<10){
            strDepartureHourOfDay="0"+strDepartureHourOfDay;
        }
        //出发时间（分）的值小于10，则拼接‘0’-》”06“
        if (departureTimeMinute<10){
            strDepartureMinute="0"+strDepartureMinute;
        }
        //到达时间（时）的值小于10，则拼接‘0’-》”06“
        if (arrivalHourOfDay<10){
            strArrivalHourOfDay="0"+strArrivalHourOfDay;
        }
        //到达时间（分）的值小于10，则拼接‘0’-》”06“
        if (arrivalMinute<10){
            strArrivalMinute="0"+strArrivalMinute;
        }

        String departure=strDepartureHourOfDay+":"+strDepartureMinute;
        String arrival=strArrivalHourOfDay+":"+strArrivalMinute;

        flightOrderInfoVo.setDeparture(departure);
        flightOrderInfoVo.setArrival(arrival);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        Date date = null;
        Date date1 = null;
        try {
            date = simpleDateFormat.parse(departure);
            date1 = simpleDateFormat.parse(arrival);
        }catch (Exception e){
            e.printStackTrace();
        }

        Long from = date.getTime();
        Long to = date1.getTime();

        int hour = (int) ((to-from) / (1000 * 60 * 60));
        int minute = (int) (((to-from) / (1000 * 60)) % 60);

        flightOrderInfoVo.setTimeDifference(hour+"时"+minute+"分");
        if (hour<=0){
            flightOrderInfoVo.setTimeDifference(minute+"分");
        }
        else if (minute<=0){
            flightOrderInfoVo.setTimeDifference(hour+"时");
        }

        return flightOrderInfoVo;
    }

    /**
     * 我的-订单列表（机票-基本信息）删除订单
     * */
    @Override
    public int updateFlightOrderInfoByOrdernum(Long customerId) {
        return flightOrderInfoMapper.updateFlightOrderInfoByOrdernum(customerId);
    }

    /**
     * 我的-订单列表（机票-基本信息）取消订单
     * */
    @Override
    public int updateFlightOrderInfoByOrdernumPnrstatus(FlightOrderInfoVo flightOrderInfoVo) {
        flightOrderInfoVo.setPnrstatus(CustomerConstants.cancelPay.getValue());
        return flightOrderInfoMapper.updateFlightOrderInfoByOrdernumPnrstatus(flightOrderInfoVo);
    }

    /**
     * 我的-订单列表（机票-基本信息）修改订单
     * */
    @Override
    public int updateFlightOrderInfoByFlightOrderInfoVo(FlightOrderInfoVo flightOrderInfoVo) {
        int count=0;
        int incount1=flightOrderInfoMapper.updateFlightOrderInfoByFlightOrderInfoVo(flightOrderInfoVo);
        Long orderId=flightOrderInfoMapper.selectFlightOrderInfoByOrdernum(flightOrderInfoVo.getOrdernum());
        flightOrderInfoVo.setOrderId(orderId);
        int incount2=flightOrderInfoTicketsMapper.updateFlightOrderInfoTicketsByFlightOrderInfoVo(flightOrderInfoVo);
        if (incount1>0 && incount2>0){
            count=1;
        }
        return count;
    }

    @Override
    public int updateFlightOrderInfoByOrdernumStatus(FlightOrderInfoVo flightOrderInfoVo) {
        flightOrderInfoVo.setPnrstatus(CustomerConstants.payd.getValue());
        return flightOrderInfoMapper.updateFlightOrderInfoByOrdernumPnrstatus(flightOrderInfoVo);
    }

    /**
     * 根据订单号获取订单信息
     * @param orderId
     * @return
     */
    @Override
    public FlightOrderInfo selectFlightOrderInfo(String orderId) {
        FlightOrderInfo orderInfo = flightOrderInfoMapper.selectFlightOrderInfoByPnr(orderId);
        return orderInfo;
    }

    @Override
    public FlightOrderInfo queryFlightOrderInfoByPnr(String pnr) {
        return flightOrderInfoMapper.queryFlightOrderInfoByPnr(pnr);
    }

    /**
     * 查询订单列表（机票）
     * */
    @Override
    public List<TicketOrder> checkTheTicketList(Long customerId, String type) {
        List<FlightOrderInfo> flightOrderInfoList = flightOrderInfoMapper.checkTheTicketList(customerId);
        List<TicketOrder> ticketOrderList = new ArrayList<>();
        List<TicketOrder> ticketOrders = new ArrayList<>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (flightOrderInfoList.size() > 0){
            for (FlightOrderInfo flightOrderInfo : flightOrderInfoList) {
                if (flightOrderInfo.getIsDeletes() != null && !flightOrderInfo.getIsDeletes().equals("true")){
                    List<FlightOrderInfoTickets> flightOrderInfoTicketsList = flightOrderInfoTicketsMapper.checkTheTicketList(flightOrderInfo.getOrderId());
                    if (flightOrderInfoTicketsList.size() > 0){
                        for (FlightOrderInfoTickets flightOrderInfoTickets : flightOrderInfoTicketsList) {
                            //单程
                            TicketOrder ticketOrder = new TicketOrder();
                            if (flightOrderInfo.getIssueTime() != null && flightOrderInfoTickets.getDepartureTime() != null){
                                String dateIssueTime = format.format(flightOrderInfo.getIssueTime());
                                String dateDepartureTime = format.format(flightOrderInfoTickets.getDepartureTime());
                                ticketOrder.setIssueTime(dateIssueTime);//出票时间
                                ticketOrder.setDepartureTime(dateDepartureTime);//出发时间
                            }
                            ticketOrder.setOrderId(flightOrderInfo.getOrderId());//机票订单基本信息ID
                            ticketOrder.setPayAmount(flightOrderInfo.getPayAmount());//支付总金额
                            ticketOrder.setAirliner(flightOrderInfoTickets.getAirliner());//航空公司
                            ticketOrder.setDeparture(flightOrderInfoTickets.getDeparture());//出港城市
                            ticketOrder.setArrival(flightOrderInfoTickets.getArrival());//到港城市
                            ticketOrder.setFlight(flightOrderInfoTickets.getFlight());//航班号
                            ticketOrder.setOrderType("机票");//订单类型
                            ticketOrder.setOrderStatus(flightOrderInfo.getOrderStatusId());//订单状态
                            if (flightOrderInfoTickets.getStopDesc() == null ||
                                    flightOrderInfoTickets.getStopDesc().equals("")){
                                ticketOrder.setStopDesc("false");//是否经停
                            }
                            else {
                                ticketOrder.setStopDesc("true");//是否经停
                            }
                            if (flightOrderInfoTickets.getTripType() != null && flightOrderInfoTickets.getTripType().equals("ow")){
                                ticketOrder.setOneAndMulti("true");
                            }
                            else {
                                ticketOrder.setOneAndMulti("false");
                            }
                            ticketOrders.add(ticketOrder);
                        }
                    }
                }
            }
            //非单程
            for (TicketOrder ticketOrder : ticketOrders) {
                for (TicketOrder temporaryTicketOrder : ticketOrders){
                    if (ticketOrder.getOneAndMulti().equals("true") &&
                            ticketOrder.getOrderId() == temporaryTicketOrder.getOrderId() &&
                            ticketOrder != temporaryTicketOrder &&
                            temporaryTicketOrder.getOneAndMulti().equals("false")){
                        ticketOrder.setRoundTripAirliner(temporaryTicketOrder.getAirliner());//往返航空公司
                        ticketOrder.setRoundTripDeparture(temporaryTicketOrder.getDeparture());//往返出港城市
                        ticketOrder.setRoundTripDepartureTime(temporaryTicketOrder.getDepartureTime());//往返出发时间
                        ticketOrder.setRoundTripArrival(temporaryTicketOrder.getArrival());//往返到港城市
                        ticketOrder.setRoundTripFlight(temporaryTicketOrder.getFlight());//往返航班号
                    }
                }
            }

            //筛选
            for (TicketOrder ticketOrder : ticketOrders){
                if (ticketOrder.getOneAndMulti().equals("true")){
                    ticketOrderList.add(ticketOrder);
                }
            }
        }
        else {
            return null;
        }
        return ticketOrderList;
    }

    public List<String> conversion(int departureMonth, int departureDay, int arrivalMonth, int arrivalDay){
        List<String> strList=new ArrayList<>();

        String strDepartureMonth=String.valueOf(departureMonth);
        String strDepartureDay=String.valueOf(departureDay);
        String strArrivalMonth=String.valueOf(arrivalMonth);
        String strArrivalDay=String.valueOf(arrivalDay);

        //出发时间（月）的值小于10，则拼接‘0’-》”06“
        if (Integer.parseInt(strDepartureMonth)<10){
            strDepartureMonth="0"+strDepartureMonth;
        }
        //出发时间（日）的值小于10，则拼接‘0’-》”06“
        if (Integer.parseInt(strDepartureDay)<10){
            strDepartureDay="0"+strDepartureDay;
        }
        //到达时间（月）的值小于10，则拼接‘0’-》”06“
        if (Integer.parseInt(strArrivalMonth)<10){
            strArrivalMonth="0"+strArrivalMonth;
        }
        //到达时间（日）的值小于10，则拼接‘0’-》”06“
        if (Integer.parseInt(strArrivalDay)<10){
            strArrivalDay="0"+strArrivalDay;
        }

        strList.add(strDepartureMonth);
        strList.add(strDepartureDay);
        strList.add(strArrivalMonth);
        strList.add(strArrivalDay);

        return strList;
    }

    //订单详情
    @Override
    public OrderDetails queryFlightOrderInfoByOrderId(String token, Long orderId) throws Exception {
        OrderDetails orderDetails = new OrderDetails();
        FlightOrderInfo flightOrderInfo = null;
        if (token != null) {
            R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
            if (customer.getCode() == 200 && customer.getData() != null) {
                Long customerId = customer.getData().getCustomerId();
                flightOrderInfo = flightOrderInfoMapper.queryFlightOrderInfoByOrderId(customerId, orderId);
            } else {
                throw new Exception("登录过期！");
            }
        } else {
            flightOrderInfo = flightOrderInfoMapper.queryFlightOrderInfoByOrderId(null, orderId);
        }
        List<Airliner> airliners = airlinerMapper.selectAirlinerList(null);
        String logo = filesService.airlineLogo(); //航司LogoUrl

        orderDetails.setStatus(flightOrderInfo.getStatus());
        orderDetails.setPnr(flightOrderInfo.getPnr()); //PNR
        orderDetails.setPnrstatus(flightOrderInfo.getPnrstatus()); //订单PNR状态
        orderDetails.setGuestPymtStsId(flightOrderInfo.getGuestPymtStsId()); //订单收银状态
        orderDetails.setTripType(flightOrderInfo.getTripType()); //行程-单程 OW   行程-往返 RT
        orderDetails.setPayAmount(flightOrderInfo.getPayAmount()); //支付总金额
        orderDetails.setCreateTime(flightOrderInfo.getCreateTime()); //订单创建时间
        orderDetails.setPayType(flightOrderInfo.getPayType()); //付款方式
        orderDetails.setDeparture(flightOrderInfo.getInfoTickets().get(0).getDeparture());
        orderDetails.setArrival(flightOrderInfo.getInfoTickets().get(0).getArrival());
        orderDetails.setPoints(flightOrderInfo.getPoints());
        orderDetails.setDepositAmount(flightOrderInfo.getDepositAmount());
        for (FlightOrderInfoTickets infoTicket : flightOrderInfo.getInfoTickets()) {
            Airliner anElse = airliners.stream().filter(airliner -> airliner.getAirlinerId().equals(infoTicket.getAirliner())).findFirst().orElse(null);
            FlightOrderDetails flightOrderDetails = new FlightOrderDetails();
            flightOrderDetails.setOrderInfoTicketsId(infoTicket.getOrderInfoTicketsId()); //主键自增
            flightOrderDetails.setAirliner(infoTicket.getAirliner()); //航空公司
            if (anElse != null)
                flightOrderDetails.setAirlinerName(anElse.getAirlinerShorter());
            flightOrderDetails.setFlight(infoTicket.getFlight()); //航班号
            flightOrderDetails.setFlightType(infoTicket.getFlightType()); //航班类型
            flightOrderDetails.setCabinGrade(infoTicket.getCabinGrade()); //仓位等级
            flightOrderDetails.setDepTerm(infoTicket.getDepTerm()); //起飞机场航站楼
            flightOrderDetails.setDepartureTime(infoTicket.getDepartureTime()); //出发时间
            flightOrderDetails.setArrTerm(infoTicket.getArrTerm()); //到达机场航站楼
            flightOrderDetails.setArrivalTime(infoTicket.getArrivalTime()); //到达时间
            flightOrderDetails.setGuestName(infoTicket.getGuestName()); //乘客姓名
            flightOrderDetails.setGuestType(infoTicket.getGuestType()); //乘客类型
            flightOrderDetails.setIdTypeId(infoTicket.getIdTypeId()); //证件类型ID
            flightOrderDetails.setGuestIdno(infoTicket.getGuestIdno()); //证件号
            flightOrderDetails.setTicketPrice(infoTicket.getTicketPrice()); //票面价
            flightOrderDetails.setTicketNo(infoTicket.getTicketNo()); //票号
            flightOrderDetails.setFuelFee(infoTicket.getFuelFee()); //燃油费
            flightOrderDetails.setAirportFee(infoTicket.getAirportFee()); //机建费
            flightOrderDetails.setOrgAirport(infoTicket.getOrgAirport());
            flightOrderDetails.setDstAirport(infoTicket.getDstAirport());
            flightOrderDetails.setCabin(infoTicket.getCabin());
            flightOrderDetails.setTripType(infoTicket.getTripType());
            flightOrderDetails.setStatus(infoTicket.getStatus());
            flightOrderDetails.setAirlineGif(logo + infoTicket.getAirliner() + ".gif");
            orderDetails.getFlightOrderDetails().add(flightOrderDetails);
            List<FlightOrderAssist> orderAssist = flightOrderAssistService.queryFlightOrderAssist(infoTicket.getOrderInfoTicketsId());
            if (orderAssist != null && orderAssist.size() > 0) {
                orderDetails.getFlightOrderAssists().addAll(orderAssist);
            }
        }
        List<FlightOrderChangeTickets> changeTicketsList = changeTicketsService.queryChangeTicketsByOrderId(orderId);
        if (changeTicketsList != null && changeTicketsList.size() > 0) {
            changeTicketsList.forEach(item -> {
                FlightChangeOrderDetails changeOrderDetails = new FlightChangeOrderDetails();
                Airliner anElse = airliners.stream().filter(airliner -> airliner.getAirlinerId().equals(item.getAirliner())).findFirst().orElse(null);
                BeanUtils.copyProperties(item, changeOrderDetails);
                if (anElse != null)
                    changeOrderDetails.setAirlinerName(anElse.getAirlinerShorter());
                orderDetails.getChangeOrderDetails().add(changeOrderDetails);
            });
        }
        FlightOrderIternary flightOrderIternary = flightOrderIternaryMapper.selectFlightOrderIternaryByOrderId(orderId);
        if (flightOrderIternary != null) {
            if (flightOrderIternary.getPostWay().equals(2L)) {
                orderDetails.setVoucher("行程单 机场取票");
                orderDetails.setTakeTicketAddress(flightOrderIternary.getTakeTicketAddress());
            } else if (flightOrderIternary.getPostWay().equals(1L)) {
                FlightDeliverAssign flightDeliverAssign = flightDeliverAssignMapper.queryFlightDeliverAssignByOrderId(orderId);
                if (flightDeliverAssign != null) {
                    orderDetails.setVoucher("行程单");
                    if (flightDeliverAssign.getPostId() != null)
                        orderDetails.setVoucherStatus("已邮寄");
                    else
                        orderDetails.setVoucherStatus("待邮寄");
                }
            }
        }

        int emailState = payService.queryEmailState(orderId);
        if (emailState != 0) {
            orderDetails.setVoucher("发票");
            if (emailState == 1)
                orderDetails.setVoucherStatus("待开票");
            else if (emailState == 2 || emailState == 3)
                orderDetails.setVoucherStatus("已开票");
        }
        return orderDetails;
    }

    //订单列表
    @Override
    public List<FlightOrderList> flightOrderInfoList(Long customerId, String status) {
        /*List<FlightOrderList> flightOrderLists = new ArrayList<>();
        List<FlightOrderInfo> orderInfo = flightOrderInfoMapper.flightOrderInfoList(customerId, status);
        for (FlightOrderInfo flightOrderInfo : orderInfo) {
            FlightOrderList orderList = new FlightOrderList();
            orderList.setOrderId(String.valueOf(flightOrderInfo.getOrderId())); //机票订单基本信息id
            orderList.setGuestPymtStsId(flightOrderInfo.getGuestPymtStsId()); //订单收银状态
            orderList.setPayAmount(flightOrderInfo.getPayAmount()); //支付总金额
            orderList.setStatus(flightOrderInfo.getStatus()); //订单状态

            Date create = flightOrderInfo.getCreateTime();
            Calendar cal = Calendar.getInstance();
            cal.setTime(create);
            cal.add(Calendar.MINUTE, 30);
            Date calDate = cal.getTime();
            Date date = new Date();

            long time = calDate.getTime();
            long dateTime = date.getTime();
            long expirationTime = (time - dateTime) / 1000;
            if (flightOrderInfo.getGuestPymtStsId().equals("waitPay")) {
                orderList.setExpirationTime(String.valueOf(expirationTime));
            }

            for (FlightOrderInfoTickets infoTicket : flightOrderInfo.getInfoTickets()) {
                FlightOrderDetailsList detailsList = new FlightOrderDetailsList();
                detailsList.setOrderInfoTicketsId(String.valueOf(infoTicket.getOrderInfoTicketsId())); //自增主键
                detailsList.setAirliner(infoTicket.getAirliner()); //航空公司
                if (infoTicket.getAirliner() != null) {
                    detailsList.setAirlinerName(airlinerService.queryAirliner(infoTicket.getAirliner()));
                }
                detailsList.setFlight(infoTicket.getFlight()); //航班号
                detailsList.setDeparture(infoTicket.getDeparture()); //出港城市
                detailsList.setArrival(infoTicket.getArrival()); //到港城市
                detailsList.setTripType(infoTicket.getTripType()); //航段类型（单程，往返中转第一程均为OW,往返第二程为RT,中转第二程为OT。老版本往返票为WM已经废弃）
                detailsList.setDepartureTime(infoTicket.getDepartureTime()); //出发时间
                detailsList.setArrivalTime(infoTicket.getArrivalTime()); //到达时间
                orderList.getOrderDetailsLists().add(detailsList);
            }
            flightOrderLists.add(orderList);
        }*/
        List<FlightOrderList> order = new ArrayList<>();
        List<FlightOrderList> orderInfo = flightOrderInfoMapper.flightOrderInfoList(customerId);
        for (FlightOrderList flightOrderList : orderInfo) {
            Date create = flightOrderList.getCreateTime();
            Calendar cal = Calendar.getInstance();
            cal.setTime(create);
            cal.add(Calendar.MINUTE, 30);
            Date calDate = cal.getTime();
            Date date = new Date();

            long time = calDate.getTime();
            long dateTime = date.getTime();
            long expirationTime = (time - dateTime) / 1000;
            if (flightOrderList.getGuestPymtStsId().equals("waitPay")) {
                flightOrderList.setExpirationTime(String.valueOf(expirationTime));
            }
            if (flightOrderList.getOrderDetailsLists() != null && flightOrderList.getOrderDetailsLists().size() > 0)
                flightOrderList.setAirlinerName(airlinerService.queryAirliner(flightOrderList.getOrderDetailsLists().get(0).getAirliner()));
            flightOrderList.getOrderDetailsLists().forEach(item -> {
                if (item.getDepAirportName() != null && item.getDepAirportName() != "") {
                    Airport depAirport = airportService.airportName(item.getDepAirportName());
                    item.setDepAirportName(depAirport.getAirportName());
                }
                if (item.getArrAirportName() != null && item.getArrAirportName() != "") {
                    Airport arrAirport = airportService.airportName(item.getArrAirportName());
                    item.setArrAirportName(arrAirport.getAirportName());
                }
            });
        }
        if (status.equals("")) {
            orderInfo.forEach(item -> {
                if (item.getStatus().equals("rescheduled") || item.getStatus().equals("changeTicketSuccess") || item.getStatus().equals("changeTicketFail")) {
                    List<FlightOrderChangeTickets> flightOrderChangeTickets = changeTicketsService.queryChangeTicketsByOrderId(Long.valueOf(item.getOrderId()));
                    flightOrderChangeTickets.forEach(items -> {
                        FlightOrderDetailsList detailsList = new FlightOrderDetailsList();
                        BeanUtils.copyProperties(items, detailsList);
                        detailsList.setOrderInfoTicketsId(String.valueOf(items.getChangeTicketId()));
                        if (items.getOrgAirport() != null && !items.getOrgAirport().equals("")) {
                            detailsList.setDepAirportCode(items.getOrgAirport());
                            Airport depAirport = airportService.airportName(items.getOrgAirport());
                            detailsList.setDepAirportName(depAirport.getAirportName());
                        }
                        if (items.getDstAirport() != null && !items.getDstAirport().equals("")) {
                            detailsList.setArrAirportCode(items.getDstAirport());
                            Airport depAirport = airportService.airportName(items.getOrgAirport());
                            detailsList.setArrAirportName(depAirport.getAirportName());
                        }
                        item.getOrderChangeDetailsLists().add(detailsList);
                    });
                }
            });
            return orderInfo;
        } else if (status.equals("waitPay")) {
            orderInfo.forEach(item -> {
                FlightOrderList orderList = new FlightOrderList();
                if (item.getStatus().equals(status)) {
                    item.getOrderDetailsLists().forEach(items -> {
                        FlightOrderDetailsList detailsList = new FlightOrderDetailsList();
                        BeanUtils.copyProperties(items, detailsList);
                        orderList.getOrderDetailsLists().add(detailsList);
                    });
                    order.add(orderList);
                    BeanUtils.copyProperties(item, orderList);
                }
            });
            return order;
        } else if (status.equals("noTravel")) {
            orderInfo.forEach(item -> {
                FlightOrderList orderList = new FlightOrderList();
                if (item.getStatus().equals(status)) {
                    item.getOrderDetailsLists().forEach(items -> {
                        FlightOrderDetailsList detailsList = new FlightOrderDetailsList();
                        BeanUtils.copyProperties(items, detailsList);
                        orderList.getOrderDetailsLists().add(detailsList);
                    });
                    order.add(orderList);
                    BeanUtils.copyProperties(item, orderList);
                }
            });
            return order;
        } else if (status.equals("changeReturn")) {
            orderInfo.forEach(item -> {
                FlightOrderList orderList = new FlightOrderList();
                if (item.getStatus().equals("refundProgress") || item.getStatus().equals("rescheduled") || item.getStatus().equals("changeTicketSuccess")
                        || item.getStatus().equals("changeTicketFail") || item.getStatus().equals("refundTicketStatus_success") || item.getStatus().equals("refundTicketFail")) {
                    item.getOrderDetailsLists().forEach(items -> {
                        FlightOrderDetailsList detailsList = new FlightOrderDetailsList();
                        BeanUtils.copyProperties(items, detailsList);
                        orderList.getOrderDetailsLists().add(detailsList);
                    });
                    BeanUtils.copyProperties(item, orderList);
                    if (item.getStatus().equals("rescheduled") || item.getStatus().equals("changeTicketSuccess") || item.getStatus().equals("changeTicketFail")) {
                        List<FlightOrderChangeTickets> flightOrderChangeTickets = changeTicketsService.queryChangeTicketsByOrderId(Long.valueOf(item.getOrderId()));
                        flightOrderChangeTickets.forEach(items -> {
                            FlightOrderDetailsList detailsList = new FlightOrderDetailsList();
                            BeanUtils.copyProperties(items, detailsList);
                            detailsList.setOrderInfoTicketsId(String.valueOf(items.getChangeTicketId()));
                            if (items.getOrgAirport() != null && !items.getOrgAirport().equals("")) {
                                detailsList.setDepAirportCode(items.getOrgAirport());
                                Airport depAirport = airportService.airportName(items.getOrgAirport());
                                detailsList.setDepAirportName(depAirport.getAirportName());
                            }
                            if (items.getDstAirport() != null && !items.getDstAirport().equals("")) {
                                detailsList.setArrAirportCode(items.getDstAirport());
                                Airport depAirport = airportService.airportName(items.getOrgAirport());
                                detailsList.setArrAirportName(depAirport.getAirportName());
                            }
                            orderList.getOrderChangeDetailsLists().add(detailsList);
                        });
                    }
                    order.add(orderList);
                }
            });
            return order;
        }
        return null;
    }

    //填写订单
    @Override
    public FlightFillOrder fillOrder(HttpServletRequest servletRequest, FlightFillOrderEnter orderEnter) throws Exception {
        String token = null;
        if (servletRequest != null){
            token = servletRequest.getHeader("token");
        }

        FlightFillOrder fillOrder = new FlightFillOrder();
        R<Customer> customer;
        if (token != null){
            customer = remoteCustomerService.getLoginCustomerByToken(token);
        }
        else if (orderEnter.customerId != null && orderEnter.customerId != 0){
            customer = remoteCustomerService.getCustomerInfo(orderEnter.customerId);
        }
        else {
            throw new Exception("没有获取会员信息");
        }
        String airlinerId = null;
        BigDecimal price = null;
        if (orderEnter.type.equals(FlightConstants.oneWay.getValue())) {
            FlightDetailsDTO details = new FlightDetailsDTO();
            FlightVo flightVo = flightService.flightDetails(customer.getData(), orderEnter.flightSearchRequest);
            airlinerId = flightVo.getFlightNo().substring(0, 2);
            for (CabinInfoVo cabinInfoVo : flightVo.getListCabinInfo()) {
                if (orderEnter.cabin.equals(cabinInfoVo.getCabin()) && orderEnter.cabinPrice.compareTo(cabinInfoVo.getPrice()) == 0) {
                    BeanUtils.copyProperties(cabinInfoVo, details);
                    price = cabinInfoVo.getPrice();
                }
            }
            BeanUtils.copyProperties(flightVo, details);
            fillOrder.getFlightDetails().add(details);
        } else if (orderEnter.type.equals(FlightConstants.transfer.getValue())) {
            String transferId = orderEnter.transferId;
            String depDate = orderEnter.flightSearchRequest.GoSearchWhere.DepDate;
            String dstAirport = orderEnter.flightSearchRequest.GoSearchWhere.DstAirport;
            String orgAirport = orderEnter.flightSearchRequest.GoSearchWhere.OrgAirport;
            FlightTransfer transfers = flightService.flightTransfers(customer.getData(), transferId, depDate, dstAirport, orgAirport);
            FlightVo flightVoZero = transfers.flightVoList.get(0);
            FlightVo flightVoOne = transfers.flightVoList.get(1);
            BigDecimal priceAdd = new BigDecimal(0);
            airlinerId = flightVoZero.getFlightNo().substring(0, 2);
            FlightDetailsDTO details = new FlightDetailsDTO();
            BeanUtils.copyProperties(flightVoZero, details);
            for (CabinInfoVo cabinInfoVo : flightVoZero.getListCabinInfo()) {
                if (orderEnter.cabin.equals(cabinInfoVo.getCabin()) && orderEnter.cabinPrice.compareTo(cabinInfoVo.getPrice()) == 0) {
                    //details.setPrice(cabinInfoVo.getPrice());
                    BeanUtils.copyProperties(cabinInfoVo, details);
                    priceAdd = priceAdd.add(cabinInfoVo.getPrice());
                }
            }
            details.setType("1");
            fillOrder.getFlightDetails().add(details);

            FlightDetailsDTO detailsOne = new FlightDetailsDTO();
            BeanUtils.copyProperties(flightVoOne, detailsOne);
            for (CabinInfoVo cabinInfoVo : flightVoOne.getListCabinInfo()) {
                if (orderEnter.cabins.equals(cabinInfoVo.getCabin()) && orderEnter.cabinsPrice.compareTo(cabinInfoVo.getPrice()) == 0) {
                    //detailsOne.setPrice(cabinInfoVo.getPrice());
                    BeanUtils.copyProperties(cabinInfoVo, detailsOne);
                    priceAdd = priceAdd.add(cabinInfoVo.getPrice());
                }
            }
            detailsOne.setType("2");
            fillOrder.getFlightDetails().add(detailsOne);
            price = priceAdd;
        } else if (orderEnter.type.equals(FlightConstants.backForth.getValue())) {
            FlightResponseDTO responseDTO = flightService.flightReturn(customer.getData(), orderEnter.flightSearchRequest);
            airlinerId = responseDTO.flightVos.getFlightNo().substring(0, 2);
            FlightDetailsDTO goDetails = new FlightDetailsDTO();
            FlightDetailsDTO backDetails = new FlightDetailsDTO();
            BigDecimal priceAdd = new BigDecimal(0);

            BeanUtils.copyProperties(responseDTO.flightVos, goDetails);
            for (CabinInfoVo cabinInfoVo : responseDTO.flightVos.getListCabinInfo()) {
                if (orderEnter.cabin.equals(cabinInfoVo.getCabin()) && orderEnter.cabinPrice.compareTo(cabinInfoVo.getPrice()) == 0) {
                    //goDetails.setPrice(cabinInfoVo.getPrice());
                    BeanUtils.copyProperties(cabinInfoVo, goDetails);
                    priceAdd = priceAdd.add(cabinInfoVo.getPrice());
                }
            }
            goDetails.setType("去");
            fillOrder.getFlightDetails().add(goDetails);

            BeanUtils.copyProperties(responseDTO.backFlightVos, backDetails);
            for (CabinInfoVo cabinInfoVo : responseDTO.backFlightVos.getListCabinInfo()) {
                if (orderEnter.cabins.equals(cabinInfoVo.getCabin()) && orderEnter.cabinsPrice.compareTo(cabinInfoVo.getPrice()) == 0) {
                    //backDetails.setPrice(cabinInfoVo.getPrice());
                    BeanUtils.copyProperties(cabinInfoVo, backDetails);
                    priceAdd = priceAdd.add(cabinInfoVo.getPrice());
                }
            }
            backDetails.setType("返");
            fillOrder.getFlightDetails().add(backDetails);
            price = priceAdd;
        }
        fillOrder.setAirlineCode(airlinerId);
        fillOrder.setSMSnotification(customer.getData().getContractPhoneOne()); //短信通知
        BigDecimal depb;

        Map<String, Object> amountMap = new HashMap<>();
        amountMap.put("id", orderEnter.customerId);

        if (token != null && !token.equals("")){
            depb = remoteCustomerService.BackDominateGold(servletRequest);
        }
        else {
            depb = remoteCustomerService.dominateGold(amountMap);
        }
        fillOrder.setDepositBusiness(depb); //预留款（金币）

        Long integralVoR;
        if (token != null && !token.equals("")){
            integralVoR = remoteCustomerService.BackDominateIntegral(servletRequest);
        }
        else {
            integralVoR = remoteCustomerService.dominateIntegral(amountMap);
        }
        Long points = integralVoR;
        fillOrder.setPoints(points); //积分

        R<CouponDto> couponDtoR;
        if (token != null && !token.equals("")){
            couponDtoR = remoteCustomerService.queyUserCouponByToken(token, price);
        }
        else {
            couponDtoR = remoteCustomerService.queyUserCouponById(orderEnter.customerId, price);
        }
        CouponDto couponDto = couponDtoR.getData();
        fillOrder.setCoupon(couponDto); //优惠券

        Map<String, Object> map = new HashMap<>();
        map.put("status", AssistProductEnum.activation.getValue());
        map.put("businessType", AssistProductEnum.flight.getValue());
        List<AssistProductApi> productList = remoteCustomerService.queryAssistProductList(map);
        fillOrder.setAssistProduct(productList); //辅营产品

        List<FlightRevisecabinprice> revisecabinprices = null;
        if (customer.getData() != null) {
            revisecabinprices = revisecabinpriceMapper.selectReviseCabinByCustomerIdCard(customer.getData().getCustCertificateNo());
            if (revisecabinprices == null)
                revisecabinprices = revisecabinpriceMapper.queryReviseCabin();
        } else {
            revisecabinprices = revisecabinpriceMapper.queryReviseCabin();
        }
        if (revisecabinprices != null && revisecabinprices.size() > 0) {
            List<FlightRevisecabinprice> revisecabinprice = revisecabinprices.stream().filter(reviseCabin -> reviseCabin.getAirlinerId().equals(orderEnter.flightSearchRequest.GoSearchWhere.FlightNo.substring(0, 2))).collect(Collectors.toList());
            if (revisecabinprice != null && revisecabinprice.size() > 0) {
                for (FlightRevisecabinprice flightRevisecabinprice : revisecabinprice) {
                    String cabin = flightRevisecabinprice.getCabin();
                    String[] splitCabin = cabin.split(",");
                    for (String spl : splitCabin) {
                        if (orderEnter.flightSearchRequest.GoSearchWhere.Cabin.equals(spl)) {
                            fillOrder.setVoucher(flightRevisecabinprice.getCredentials());
                            break;
                        }
                        else
                            fillOrder.setVoucher("行程单");
                    }
                    if (fillOrder.getVoucher() != null && fillOrder.getVoucher().equals("发票"))
                        break;
                }
            } else
                fillOrder.setVoucher("行程单");
        } else
            fillOrder.setVoucher("行程单");
        return fillOrder;
    }

    //订单收银台
    @Override
    public FlightOrderCashier selectFlightOrderInfo(String token, Long orderId, String businessType) {
        FlightOrderCashier orderCashier = new FlightOrderCashier();
        R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
        FlightOrderInfo orderInfo = flightOrderInfoMapper.selectFlightOrderInfo(orderId, customer.getData().getCustomerId());
        Long expireTime = redisService.redisTemplate.getExpire("flight" + customer.getData().getCustomerId() + "o" + orderId);
        orderCashier.setTripType(orderInfo.getTripType());
        orderCashier.setPayAmount(orderInfo.getPayAmount());
        orderCashier.setGuestPymtStsId(orderInfo.getGuestPymtStsId());
        for (FlightOrderInfoTickets infoTicket : orderInfo.getInfoTickets()) {
            FlightOrderItemCashier orderItemCashier = new FlightOrderItemCashier();
            orderItemCashier.setDeparture(infoTicket.getDeparture());
            orderItemCashier.setArrival(infoTicket.getArrival());
            orderItemCashier.setDepartureTime(infoTicket.getDepartureTime());
            orderItemCashier.setArrivalTime(infoTicket.getArrivalTime());
            orderItemCashier.setSegmentType(infoTicket.getTripType());
            orderItemCashier.setFlight(infoTicket.getFlight());
            orderItemCashier.setDepTerm(infoTicket.getDepTerm());
            orderItemCashier.setArrTerm(infoTicket.getArrTerm());
            orderCashier.getOrderItemCashiers().add(orderItemCashier);
        }
        if (expireTime != null && expireTime > 0) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("businessType", businessType);
            List<PayTypeApi> payTypes = payService.queryPayType(businessType);
            for (PayTypeApi payType : payTypes) {
                PayTypeVo typeVo = new PayTypeVo();
                typeVo.setPayId(payType.getPayId());
                typeVo.setPayName(payType.getPayName());
                typeVo.setPayType(payType.getPayType());
                typeVo.setPayInfo(payType.getPayInfo());
                orderCashier.getPayType().add(typeVo);
            }
            orderCashier.setExpiredTime(String.valueOf(expireTime));
        } else {
            orderCashier.setExpiredTime("订单已超时！");
        }
        return orderCashier;
    }

    //微信小程序支付
    @Override
    public Map<String, Object> wechatPay(String openId, String orderNumber, BigDecimal amount, String type, HttpServletRequest request) throws Exception {
        FlightOrderInfo flightOrderInfo = selectFlightOrderInfo(orderNumber);

        if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
            flightOrderInfo.setPayAmount(flightOrderInfo.getPayAmount().subtract(amount));
            flightOrderInfo.setDepositAmount(amount);
            int i = flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
            if (i <= 0){
                throw new Exception("修改订单预留款失败");
            }

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登陆已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票微信小程序支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(flightOrderInfo.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(flightOrderInfo.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "机票微信小程序支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        String notifyUrl = "/flight/callback/wechatPayCallback";
        R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, flightOrderInfo.getPayAmount(), orderNumber, notifyUrl);
        if (wechatJSAPIPayParam.getCode() == 200) {
            return wechatJSAPIPayParam.getData();
        }
        return null;
    }

    //改签微信小程序支付
    @Override
    public Map<String, Object> wechatPayChange(String openId, String orderNumber, BigDecimal payAmount, BigDecimal amount, String type, HttpServletRequest request) throws Exception {
        FlightOrderChangeTickets orderChangeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(orderNumber));

        if (amount != null && amount.compareTo(new BigDecimal(0)) > 0){
            payAmount = payAmount.subtract(amount);

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登陆已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票改签微信小程序支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(type);
            depositBusiness.setCustomerId(orderChangeTickets.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(orderChangeTickets.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", aLong);
            map.put("remark", "机票改签微信小程序支付");
            boolean b = remoteCustomerService.manageAudit(map);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsMapper.selectOrderInfoTicketByOrderId(orderChangeTickets.getOrderId());
        if (payAmount.compareTo(new BigDecimal(0)) == 0) {
            MoOrderChangeRequest changeRequest = new MoOrderChangeRequest();
            ChangeSegementInfo segementInfo = new ChangeSegementInfo();
            segementInfo.TakeoffDate = orderChangeTickets.getDepartureTime();
            segementInfo.ArrivalTime = orderChangeTickets.getArrivalTime();
            segementInfo.DestinFlight = orderChangeTickets.getFlight().substring(2);
            segementInfo.NewDPort = infoTickets.get(0).getOrgAirport();
            segementInfo.NewAPort = infoTickets.get(0).getDstAirport();
            segementInfo.airline = orderChangeTickets.getAirliner();
            segementInfo.NewClass = orderChangeTickets.getCabin();
            changeRequest.ListChangeSegementInfo.add(segementInfo);
            changeRequest.newOrderId = orderNumber;
            changeRequest.pnr = orderChangeTickets.getPnr();
            changeRequest.ticketNo = orderChangeTickets.getOldTicketNo();
            changeRequest.TicketFee = orderChangeTickets.getTicketPrice();
            changeRequest.PayAmount = payAmount;
            changeRequest.channelType = 14;
            MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
            orderChangeTickets.setChangeFee(payAmount);
            changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
            Map<String, Object> map = new HashMap<>();
            map.put("ApplicationId", response.ApplicationId);
            map.put("PayAmount", response.PayAmount);
            return map;
        } else {
            String notifyUrl = "/flight/callback/wechatPayChangeCallback";
            R<Map> wechatJSAPIPayParam = payService.getWechatJSAPIPayParam(openId, payAmount, orderNumber, notifyUrl);
            if (wechatJSAPIPayParam.getCode() == 200) {
                return wechatJSAPIPayParam.getData();
            }
        }
        return null;
    }

    //银联二维码支付码获取
    @Override
    public UnionPayQRCodeResponseApi getQRCode(Map<String, String> map, HttpServletRequest request) throws Exception {
        String orderId = map.get("billNo");
        FlightOrderInfo info = flightOrderInfoMapper.selectFlightOrderInfoByPnr(orderId);

        BigDecimal count = info.getPayAmount();
        BigDecimal amount = null;
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount"));
        }
        if (amount!=null && amount.intValue()>0)
        {
            count = count.subtract(amount);

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null)
            {
                throw new Exception("登录已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票银联二维码支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(map.get("type"));
            depositBusiness.setCustomerId(info.getCustomerId());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(info.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0)
            {
                throw new Exception("添加预留款失败");
            }

            Map<String, Object> auditMap = new HashMap<>();
            auditMap.put("id", aLong);
            auditMap.put("remark", "机票银联二维码支付");
            boolean b = remoteCustomerService.manageAudit(auditMap);
            if (!b)
            {
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        Map<String, String> QRMap = new HashMap<>();
        String billNo = "5676" + orderId;
        QRMap.put("billNo", billNo);
        QRMap.put("totalAmount", String.valueOf(count.multiply(new BigDecimal(100)).longValue()));
        QRMap.put("notifyUrl", "http://106.38.39.137:8080/flight/callback/unionPayQRCodeCallback");

        UnionPayQRCodeResponseApi qrCode = payService.getQRCode(QRMap);
        if (qrCode.getErrCode().equals("SUCCESS")) {
            FlightOrderInfo orderInfo = new FlightOrderInfo();
            orderInfo.setOrderId(Long.valueOf(orderId));
            orderInfo.setQrCode(qrCode.getBillQRCode());
            flightOrderInfoMapper.updateFlightOrderInfo(orderInfo);
        }
        return qrCode;
    }

    //改签订单银联二维码支付码获取
    @Override
    public UnionPayQRCodeResponseApi getQRCodeChange(Map<String, String> map, HttpServletRequest request) throws Exception {
        String orderId = map.get("billNo");
        FlightOrderChangeTickets orderChangeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(orderId));
        UnionPayQRCodeResponseApi qrCode = new UnionPayQRCodeResponseApi();

        BigDecimal payAmount = new BigDecimal(map.get("payAmount"));

        if (map.get("amount") != null && !map.get("amount").equals("")){
            BigDecimal count = new BigDecimal(map.get("amount"));
            payAmount = payAmount.subtract(count);

            String token = request.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登录已过期");
            }

            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("机票改签银联二维码支付");
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(map.get("type"));
            depositBusiness.setCustomerId(orderChangeTickets.getCustomerId());
            depositBusiness.setDetailamount(count);
            depositBusiness.setChangetype(2l);
            depositBusiness.setLockState("false");
            depositBusiness.setOrderId(orderChangeTickets.getOrderId());
            depositBusiness.setDrawState("false");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("添加预留款记录失败");
            }

            Map<String, Object> auditMap = new HashMap<>();
            auditMap.put("id", aLong);
            auditMap.put("remark", "机票改签银联二维码支付");
            boolean b = remoteCustomerService.manageAudit(auditMap);
            if (!b){
                throw new Exception("审核失败，请进行人工审核");
            }
        }

        List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsMapper.selectOrderInfoTicketByOrderId(orderChangeTickets.getOrderId());
        if (payAmount.compareTo(new BigDecimal(0)) == 0) {
            MoOrderChangeRequest changeRequest = new MoOrderChangeRequest();
            ChangeSegementInfo segementInfo = new ChangeSegementInfo();
            segementInfo.TakeoffDate = orderChangeTickets.getDepartureTime();
            segementInfo.ArrivalTime = orderChangeTickets.getArrivalTime();
            segementInfo.DestinFlight = orderChangeTickets.getFlight().substring(2);
            segementInfo.NewDPort = infoTickets.get(0).getOrgAirport();
            segementInfo.NewAPort = infoTickets.get(0).getDstAirport();
            segementInfo.airline = orderChangeTickets.getAirliner();
            segementInfo.NewClass = orderChangeTickets.getCabin();
            changeRequest.ListChangeSegementInfo.add(segementInfo);
            changeRequest.newOrderId = orderId;
            changeRequest.pnr = orderChangeTickets.getPnr();
            changeRequest.ticketNo = orderChangeTickets.getOldTicketNo();
            changeRequest.TicketFee = orderChangeTickets.getTicketPrice();
            changeRequest.PayAmount = payAmount;
            changeRequest.channelType = 14;
            MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
            if (response.IsSuccess) {
                FlightOrderInfoTickets tickets = new FlightOrderInfoTickets();
                tickets.setOrderId(orderChangeTickets.getOrderId());
                tickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                tickets.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
                flightOrderInfoTicketsMapper.updateFlightOrderInfoTicket(tickets);
            }
            orderChangeTickets.setChangeFee(payAmount);
            changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
            qrCode.setErrCode("SUCCESS");
            qrCode.setErrMsg("改签申请成功");
            qrCode.setBillNo(response.ApplicationId);
            return qrCode;
        } else {
            if (payAmount.compareTo(new BigDecimal(0)) == 0){
                FlightOrderChangeTickets tmpOrderChangeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(orderId));
                List<FlightOrderInfoTickets> TmpInfoTickets = flightOrderInfoTicketsService.selectOrderInfoTicketByOrderId(orderChangeTickets.getOrderId());

                AirReIssuePriceRequest priceRequest = new AirReIssuePriceRequest();
                priceRequest.setDepartureTime(String.valueOf(tmpOrderChangeTickets.getDepartureTime()));
                priceRequest.setArrivalTime(String.valueOf(tmpOrderChangeTickets.getArrivalTime()));
                priceRequest.setFlightNo(tmpOrderChangeTickets.getFlight());
                priceRequest.setCabin(tmpOrderChangeTickets.getCabin());
                priceRequest.setTicketNo(tmpOrderChangeTickets.getOldTicketNo());
                priceRequest.setOrderId(tmpOrderChangeTickets.getPnr());
                priceRequest.setEquipment(tmpOrderChangeTickets.getPlaneStyle());
                priceRequest.setDifferencePrice(true);
                ReIssuePriceResponse price = flightService.testAirReIssuePrice(priceRequest);

                MoOrderChangeRequest changeRequest = new MoOrderChangeRequest();
                ChangeSegementInfo segementInfo = new ChangeSegementInfo();
                segementInfo.TakeoffDate = tmpOrderChangeTickets.getDepartureTime();
                segementInfo.ArrivalTime = tmpOrderChangeTickets.getArrivalTime();
                segementInfo.DestinFlight = tmpOrderChangeTickets.getFlight().substring(2);
                segementInfo.NewDPort = TmpInfoTickets.get(0).getOrgAirport();
                segementInfo.NewAPort = TmpInfoTickets.get(0).getDstAirport();
                segementInfo.airline = tmpOrderChangeTickets.getAirliner();
                segementInfo.NewClass = tmpOrderChangeTickets.getCabin();
                segementInfo.PlaneStyle = tmpOrderChangeTickets.getPlaneStyle();
                changeRequest.ListChangeSegementInfo.add(segementInfo);
                changeRequest.newOrderId = orderId;
                changeRequest.pnr = tmpOrderChangeTickets.getPnr();
                changeRequest.ticketNo = tmpOrderChangeTickets.getOldTicketNo();
                changeRequest.TicketFee = tmpOrderChangeTickets.getTicketPrice();
                changeRequest.PayAmount = new BigDecimal(price.getPayPrice());
                changeRequest.channelType = 14;
                if (!tmpOrderChangeTickets.getStatus().equals(FlightOrderConstants.ticketing.getValue())) {
                    MoOrderChangeResponse changeResponse = flightService.ticketChangeFlight(changeRequest);
                    if (changeResponse.IsSuccess) {
                        FlightOrderInfoTickets tickets = new FlightOrderInfoTickets();
                        tickets.setOrderId(tmpOrderChangeTickets.getOrderId());
                        tickets.setTicketNo(tmpOrderChangeTickets.getOldTicketNo());
                        tickets.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
                        flightOrderInfoTicketsService.updateFlightOrderInfoTicket(tickets);
                    }
                    tmpOrderChangeTickets.setChangeFee(new BigDecimal(price.getPayPrice()));
                    tmpOrderChangeTickets.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                    Long billNo = System.currentTimeMillis() / 1000;
                    tmpOrderChangeTickets.setBillNo(billNo.toString());
                    tmpOrderChangeTickets.setStatus(FlightOrderConstants.ticketing.getValue());
                    changeTicketsService.updateFlightOrderChangeTickets(tmpOrderChangeTickets);
                    System.out.println("改签单号：" + changeResponse.ApplicationId);
                }
            }

            Map<String, String> QRMap = new HashMap<>();
            String billNo = "5676" + orderId;
            QRMap.put("billNo", billNo);
            QRMap.put("totalAmount", String.valueOf(payAmount.multiply(new BigDecimal(100)).longValue()));
            QRMap.put("notifyUrl", "http://106.38.39.137:8080/flight/callback/changeUnionPayQRCodeCallback");
            qrCode = payService.getQRCode(QRMap);
            if (qrCode.getErrCode().equals("SUCCESS")) {
                orderChangeTickets.setQrCode(qrCode.getBillQRCode());
                changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
            }
            return qrCode;
        }
    }

    //机票分析（未使用）
    @Override
    public FlightAnalysisDTO flightAnalysis(Long customerId, String startDate, String endDate) {
        FlightAnalysisDTO flightAnalysis = new FlightAnalysisDTO();
        StringBuilder builder = new StringBuilder();
        if (endDate != null && endDate != "") {
            builder.append(endDate);
            builder.append(" 23:59:59");
        }
        List<FlightOrderInfo> orderInfoList = flightOrderInfoMapper.flightAnalysis(customerId, startDate, builder.toString());
        List<FlightOrderInfoTickets> infoTicketsList = orderInfoTicketsService.flightAnalysis(customerId, startDate, builder.toString());

        List<FlightOrderInfo> eightUnder = new ArrayList<>();
        List<FlightOrderInfo> eightThousand = new ArrayList<>();
        List<FlightOrderInfo> thousandFive = new ArrayList<>();
        List<FlightOrderInfo> fiveTwoThousand = new ArrayList<>();
        List<FlightOrderInfo> twoThousandAbove = new ArrayList<>();
        for (FlightOrderInfo flightOrderInfo : orderInfoList) {
            if (flightOrderInfo.getPayAmount().compareTo(new BigDecimal(800)) == -1) {
                eightUnder.add(flightOrderInfo);
            } else if (flightOrderInfo.getPayAmount().compareTo(new BigDecimal(800)) == 1 && flightOrderInfo.getPayAmount().compareTo(new BigDecimal(1000)) == -1) {
                eightThousand.add(flightOrderInfo);
            } else if (flightOrderInfo.getPayAmount().compareTo(new BigDecimal(1000)) == 1 && flightOrderInfo.getPayAmount().compareTo(new BigDecimal(1500)) == -1) {
                thousandFive.add(flightOrderInfo);
            } else if (flightOrderInfo.getPayAmount().compareTo(new BigDecimal(1500)) == 1 && flightOrderInfo.getPayAmount().compareTo(new BigDecimal(2000)) == -1) {
                fiveTwoThousand.add(flightOrderInfo);
            } else if (flightOrderInfo.getPayAmount().compareTo(new BigDecimal(2000)) == 1) {
                twoThousandAbove.add(flightOrderInfo);
            }
        }


        List<FlightOrderInfoTickets> ca = infoTicketsList.stream().filter(item -> item.getAirliner().equals("CA")).collect(Collectors.toList()); //国航
        List<FlightOrderInfoTickets> zh = infoTicketsList.stream().filter(item -> item.getAirliner().equals("ZH")).collect(Collectors.toList()); //深航
        List<FlightOrderInfoTickets> hu = infoTicketsList.stream().filter(item -> item.getAirliner().equals("HU")).collect(Collectors.toList()); //海航
        List<FlightOrderInfoTickets> mu = infoTicketsList.stream().filter(item -> item.getAirliner().equals("MU")).collect(Collectors.toList()); //东航
        List<FlightOrderInfoTickets> uuu = infoTicketsList.stream().filter(item -> item.getAirliner().equals("3U")).collect(Collectors.toList()); //川航
        List<FlightOrderInfoTickets> cz = infoTicketsList.stream().filter(item -> item.getAirliner().equals("CZ")).collect(Collectors.toList()); //南航

        List<FlightOrderInfoTickets> y = infoTicketsList.stream().filter(item -> item.getCabinGrade().equals("Y")).collect(Collectors.toList());  //经济舱
        List<FlightOrderInfoTickets> economy = infoTicketsList.stream().filter(item -> item.getCabinGrade().equals("ECONOMY")).collect(Collectors.toList());  //经济舱
        List<FlightOrderInfoTickets> c = infoTicketsList.stream().filter(item -> item.getCabinGrade().equals("C")).collect(Collectors.toList());  //公务舱
        List<FlightOrderInfoTickets> j = infoTicketsList.stream().filter(item -> item.getCabinGrade().equals("J")).collect(Collectors.toList());  //公务舱
        List<FlightOrderInfoTickets> f = infoTicketsList.stream().filter(item -> item.getCabinGrade().equals("F")).collect(Collectors.toList());  //头等舱

        int flightNumber = ca.size() + zh.size() + hu.size() + mu.size() + uuu.size() + cz.size();
        int otherNumber = infoTicketsList.size() - flightNumber;

        int other = y.size() + economy.size() + c.size() + j.size() + f.size();
        int otherCabin = infoTicketsList.size() - other;

        flightAnalysis.setCaNumber(ca.size());
        flightAnalysis.setZhNumber(zh.size());
        flightAnalysis.setHuNumber(hu.size());
        flightAnalysis.setMuNumber(mu.size());
        flightAnalysis.setUuuNumber(uuu.size());
        flightAnalysis.setCzNumber(cz.size());
        flightAnalysis.setOtherNumber(otherNumber);

        flightAnalysis.setEconomyCabin(y.size() + economy.size());
        flightAnalysis.setBusinessCabin(c.size() + j.size());
        flightAnalysis.setFirstCabin(f.size());
        flightAnalysis.setOtherCabin(otherCabin);

        flightAnalysis.setEightUnder(eightUnder.size());
        flightAnalysis.setEightThousand(eightThousand.size());
        flightAnalysis.setThousandFive(thousandFive.size());
        flightAnalysis.setFiveTwoThousand(fiveTwoThousand.size());
        flightAnalysis.setTwoThousandAbove(twoThousandAbove.size());
        return flightAnalysis;
    }

    //机票分析
    @Override
    public List<AnalysisFlightDTO> analysisFlight(Long customerId, AnalysisFlightVO analysisFlight) {
        List<AnalysisFlightDTO> analysisFlightDTOS = new ArrayList<>();
        List<FlightOrderInfoTickets> ticketsList = flightOrderInfoTicketsMapper.analysisFlight(customerId, analysisFlight.getAirliner(), analysisFlight.getCabin(), analysisFlight.getId(), analysisFlight.getStartDate(), analysisFlight.getEndDate());
        for (FlightOrderInfoTickets tickets : ticketsList) {
            AnalysisFlightDTO analysisFlightDTO = new AnalysisFlightDTO();
            BeanUtils.copyProperties(tickets, analysisFlightDTO);
            if (tickets.getInsuranceID() != null && !tickets.getInsuranceID().equals("")) {
                String[] split = tickets.getInsuranceID().split(",");
                for (String id : split) {
                    AssistProduct assistProduct = new AssistProduct();
                    R<AssistProductApi> assistProductApiR = remoteCustomerService.queryAssistProduct(Long.valueOf(id));
                    if (assistProductApiR.getData() != null && assistProductApiR.getCode() == 200) {
                        BeanUtils.copyProperties(assistProductApiR.getData(), assistProduct);
                        analysisFlightDTO.getAssistProducts().add(assistProduct);
                    }
                }
            }
            analysisFlightDTOS.add(analysisFlightDTO);
        }
        return analysisFlightDTOS;
    }

    //机票订单详情（CRM）
    @Override
    public OrderFlightDetails orderFlightDetails(String orderId) {
        OrderFlightDetails flightDetails = new OrderFlightDetails();
        if (orderId.indexOf("-")==-1)
        {
            List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(Long.valueOf(orderId));
            List<FlightOutticketLog> logList = flightOutticketLogService.queryLogByOrderId(Long.valueOf(orderId));

            for (FlightOrderInfoTickets infoTicket : infoTickets) {
                PassengerInformation information = new PassengerInformation();
                BeanUtils.copyProperties(infoTicket, information);
                List<FlightOrderAssist> flightOrderAssist  = flightOrderAssistMapper.selectOrderAssistByOrderTicketId(infoTicket.getOrderInfoTicketsId());
                if (CollectionUtil.isNotEmpty(flightOrderAssist))
                {
                    information.getLstFlightOrderAssist().addAll(flightOrderAssist);
                }
                flightDetails.getPassenger().add(information);
            }

            for (FlightOutticketLog flightOutticketLog : logList) {
                FlightOutticketLogVO outticketLog = new FlightOutticketLogVO();
                BeanUtils.copyProperties(flightOutticketLog, outticketLog);
                flightDetails.getOutticketLogs().add(outticketLog);
            }
            OrderFlightInfoVO info = new OrderFlightInfoVO();
            FlightOrderInfo orderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(orderId));
            BeanUtils.copyProperties(orderInfo, flightDetails);
            BeanUtils.copyProperties(orderInfo, info);
            flightDetails.setOrderInfo(info);
            flightDetails.setId(String.valueOf(orderInfo.getOrderId()));
        }
        List<RebookVo> rebookVoList = new ArrayList<>();//改签信息
        List<RebookVo> refundVoList = new ArrayList<>();//退票信息

        List<FlightOrderChange> flightOrderChanges = flightOrderChangeMapper.queryFlightOrderChangeById(orderId);
        if (flightOrderChanges != null){
            for (FlightOrderChange flightOrderChange : flightOrderChanges) {
                List<FlightOrderChangeTickets> flightOrderChangeTickets = flightOrderChangeTicketsMapper.selectFlightOrderChangeTickets(flightOrderChange.getChangeOrderId());
                if (flightOrderChangeTickets != null && flightOrderChangeTickets.size() > 0){
                    for (FlightOrderChangeTickets flightOrderChangeTicket : flightOrderChangeTickets) {
                        RebookVo rebookVo = new RebookVo();
                        rebookVo.setChangeTicketId(flightOrderChangeTicket.getChangeTicketId());
                        rebookVo.setFlight(flightOrderChangeTicket.getFlight());
                        rebookVo.setChangeOrderId(flightOrderChangeTicket.getChangeOrderId());
                        rebookVo.setAirliner(flightOrderChangeTicket.getAirliner());
                        rebookVo.setRefundNunmber(flightOrderChange.getRefundNumber());
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        rebookVo.setTicktNo(flightOrderChangeTicket.getTicketNo());
                        rebookVo.setDepartureTime(format.format(flightOrderChangeTicket.getDepartureTime()));
                        rebookVo.setCabin(flightOrderChangeTicket.getCabin());
                        rebookVo.setArrivalTime(format.format(flightOrderChangeTicket.getArrivalTime()));
                        rebookVo.setPlaneStyle(flightOrderChangeTicket.getPlaneStyle());
                        rebookVo.setPayType(flightOrderChangeTicket.getPayType());
                        rebookVo.setStatus(flightOrderChangeTicket.getStatus());
                        rebookVo.setGuestName(flightOrderChangeTicket.getGuestName());

                        //退票
                        if (flightOrderChange.getChangeType().equals("refund")){
                            refundVoList.add(rebookVo);
                        }
                        else if (flightOrderChange.getChangeType().equals("change")){//改签
                            rebookVoList.add(rebookVo);
                        }
                    }
                }
            }
        }
        flightDetails.setRebookVoList(rebookVoList);
        flightDetails.setRefundVoList(refundVoList);
        return flightDetails;
    }

    /**
     * 机票退票详情（CRM）
     * */
    @Override
    public OrderFlightDetails refundOrderFlight(String orderId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        OrderFlightDetails flightDetails = new OrderFlightDetails();
        List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(Long.valueOf(orderId));

        for (FlightOrderInfoTickets infoTicket : infoTickets) {
            PassengerInformation information = new PassengerInformation();
            BeanUtils.copyProperties(infoTicket, information);
            flightDetails.getPassenger().add(information);
        }

        FlightOrderInfo orderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(orderId));
        flightDetails.setOrderNum(orderInfo.getOrderId().toString());
        BeanUtils.copyProperties(orderInfo, flightDetails);

        List<OutboundVo> outboundVoList = null;
        OutboundVo journeyVo = null;

        if (orderInfo.getTripType().equals("ow")){
            for (FlightOrderInfoTickets infoTicket : infoTickets) {
                if ((outboundVoList == null && infoTicket.getTripType().equals("ow")) ||
                        (outboundVoList != null && infoTicket.getTripType().equals("ot"))){
                    outboundVoList = new ArrayList<>();
                    OutboundVo outboundVo = new OutboundVo();
                    outboundVo.setOutbound(infoTicket.getDeparture());
                    outboundVo.setPosition(infoTicket.getCabinGrade());
                    outboundVo.setFlight(infoTicket.getFlight());
                    outboundVo.setFlightTime(format.format(infoTicket.getDepartureTime()));
                    outboundVo.setArrivalTime(format.format(infoTicket.getArrivalTime()));
                    outboundVo.setAirline(infoTicket.getAirliner());
                    outboundVoList.add(outboundVo);
                }
                else {
                    throw new Exception(infoTicket.getOrderInfoTicketsId() + "没有明确的单程往返信息");
                }
            }
        }
        else if (orderInfo.getTripType().equals("rt")){
            for (FlightOrderInfoTickets infoTicket : infoTickets) {
                if (outboundVoList == null && infoTicket.getTripType().equals("ow")){
                    outboundVoList = new ArrayList<>();
                    OutboundVo outboundVo = new OutboundVo();
                    outboundVo.setOutbound(infoTicket.getDeparture());
                    outboundVo.setPosition(infoTicket.getCabinGrade());
                    outboundVo.setFlight(infoTicket.getFlight());
                    outboundVo.setFlightTime(format.format(infoTicket.getDepartureTime()));
                    outboundVo.setArrivalTime(format.format(infoTicket.getArrivalTime()));
                    outboundVo.setAirline(infoTicket.getAirliner());
                    outboundVoList.add(outboundVo);
                }
                else if (journeyVo == null && infoTicket.getTripType().equals("rt")){
                    journeyVo = new OutboundVo();
                    journeyVo.setOutbound(infoTicket.getDeparture());
                    journeyVo.setPosition(infoTicket.getCabinGrade());
                    journeyVo.setFlight(infoTicket.getFlight());
                    journeyVo.setFlightTime(format.format(infoTicket.getDepartureTime()));
                    journeyVo.setArrivalTime(format.format(infoTicket.getArrivalTime()));
                    journeyVo.setAirline(infoTicket.getAirliner());
                }
                else {
                    throw new Exception(infoTicket.getOrderInfoTicketsId() + "没有明确的单程往返信息");
                }
            }
        }
        else {
            throw new Exception(orderId + "没有明确的单程往返信息");
        }

        flightDetails.setOutboundVo(outboundVoList);
        flightDetails.setJourneyVo(journeyVo);

        PriceDetailsVo priceDetailsVo = new PriceDetailsVo();
        if (infoTickets.get(0).getTicketPrice() != null && infoTickets.get(0).getTicketPrice().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setFaceValue(infoTickets.get(0).getTicketPrice().toString());
        }

        if (infoTickets.get(0).getAirportFee() != null && infoTickets.get(0).getAirportFee().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setMachineCost(infoTickets.get(0).getAirportFee().toString());
        }

        if (infoTickets.get(0).getFuelFee() != null && infoTickets.get(0).getFuelFee().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setFuelCosts(infoTickets.get(0).getFuelFee().toString());
        }

        if (infoTickets.get(0).getInsuranceAmount() != null && infoTickets.get(0).getInsuranceAmount().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setInsurance(infoTickets.get(0).getInsuranceAmount().toString());
        }

        if (orderInfo.getAdditionalFee() != null && orderInfo.getAdditionalFee().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setAdditionalFeeOne(orderInfo.getAdditionalFee().toString());
        }

        if (orderInfo.getPayAmount() != null && orderInfo.getPayAmount().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setActuallyPayable(orderInfo.getPayAmount().toString());
        }

        if (orderInfo.getTicketAmount() != null && orderInfo.getTicketAmount().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setTotalFare(orderInfo.getTicketAmount().toString());
        }

        if (orderInfo.getPayMinus() != null && orderInfo.getPayMinus().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setDiscount(orderInfo.getPayMinus().toString());
        }

        if (orderInfo.getGuestNum() != null && orderInfo.getGuestNum() != 0){
            priceDetailsVo.setTicketsNumber(orderInfo.getGuestNum().toString());
        }

        flightDetails.setPriceDetailsVo(priceDetailsVo);

        InformationVo informationVo = new InformationVo();
        informationVo.setTicketingPoint(orderInfo.getGetticketPartner());
        if (orderInfo.getIssueTime() != null){
            informationVo.setDeliveryMethod(format.format(orderInfo.getIssueTime()));
        }

        informationVo.setContact(orderInfo.getContactName());
        informationVo.setContactInformation(orderInfo.getContactMobile());
        if (orderInfo.getAssignDate() != null){
            informationVo.setAssignDate(format.format(orderInfo.getAssignDate()));
        }
        if (orderInfo.getDeliverFee() != null && orderInfo.getDeliverFee().compareTo(new BigDecimal(0)) > 0){
            informationVo.setDeliverFee(orderInfo.getDeliverFee().toString());
        }
        flightDetails.setInformationVo(informationVo);

        return flightDetails;
    }

    //改签核对-核对订单信息
    @Override
    public ChangeFlightOrder changeFlightOrder(String orderId, String ticketNo) {
        ChangeFlightOrder flightOrder = new ChangeFlightOrder();
        FlightOrderChangeTickets changeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(orderId));
        List<FlightOrderInfoTickets> ticketsList = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(changeTickets.getOrderId());
        String logo = filesService.airlineLogo();
        ChangeFlight flight = new ChangeFlight();
        ChangeFlight changeFlight = new ChangeFlight();
        changeFlight.setAirliner(airlinerService.queryAirliner(changeTickets.getAirliner()));
        changeFlight.setAirlineGif(logo + changeTickets.getAirliner() + ".gif");
        BeanUtils.copyProperties(changeTickets, changeFlight);
        flightOrder.setNewFlight(changeFlight);
        for (FlightOrderInfoTickets flightOrderInfoTickets : ticketsList) {
            if (flightOrderInfoTickets.getTicketNo().equals(ticketNo)) {
                flight.setPlaneStyle(flightOrderInfoTickets.getFlightType());
                flight.setAirliner(airlinerService.queryAirliner(flightOrderInfoTickets.getAirliner()));
                flight.setAirlineGif(logo + flightOrderInfoTickets.getAirliner() + ".gif");
                BeanUtils.copyProperties(flightOrderInfoTickets, flight);
                BeanUtils.copyProperties(flightOrderInfoTickets, flightOrder);
            }
        }
        flightOrder.setOldFlight(flight);
        flightOrder.setPnr(changeTickets.getPnr());
        return flightOrder;
    }

    //机票订单列表（CRM）
    @Override
    public List<FlightOrderListVO> flightOrderList(FlightOrderDTOCRM order) {
        StringBuilder builder;
        if (order.getDepartureTimeEnd() != null && order.getDepartureTimeEnd() != "") {
            builder = new StringBuilder();
            builder.append(order.getDepartureTimeEnd());
            builder.append(" 23:59:59");
            order.setDepartureTimeEnd(builder.toString());
        }

        if (order.getArrivalTimeEnd() != null && order.getArrivalTimeEnd() != "") {
            builder = new StringBuilder();
            builder.append(order.getArrivalTimeEnd());
            builder.append(" 23:59:59");
            order.setArrivalTimeEnd(builder.toString());
        }
        if (order.getCardNumber() != null && !order.getCardNumber().equals("")) {
            CustomerCard customerCard = remoteCustomerService.selectCustomerCard(order.getCardNumber());
            if (null != customerCard)
                order.setCustomerId(customerCard.getCustomerId());
        }
        if (null != order.getCustomerName() && "" != order.getCustomerName()) {
            Customer customer = new Customer();
            customer.setCustomerName(order.getCustomerName());
            List<Customer> customers = remoteCustomerService.customerList(customer);
            if (null != customers && 0 != customers.size())
                order.setCustomerId(customers.get(0).getCustomerId());
        }
        if (null != order.getEmployeeName() && "" != order.getEmployeeName()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", order.getEmployeeName());
            List<Long> longs = remoteCustomerService.employeeIdList(map);
            if (null != longs && 0 != longs.size())
                order.setEmployeeId(longs.get(0));
        }
        if (null != order.getFlightSegmentsInformation() && "" != order.getFlightSegmentsInformation()) {
            order.setOrgAirport(order.getFlightSegmentsInformation().substring(0, 3));
            order.setDstAirport(order.getFlightSegmentsInformation().substring(3));
        }

        List<FlightOrderListVO> orderList = flightOrderInfoMapper.flightOrderList(order);
        orderList.forEach(item -> {
            List<FlightOrderInfoTickets> ticketsList = flightOrderInfoTicketsMapper.selectOrderInfoTicketByOrderId(Long.valueOf(item.getOrderId()));
            ticketsList.forEach(itemTickets -> {
                FlightOrderTicketsList tickets = new FlightOrderTicketsList();
                BeanUtils.copyProperties(itemTickets, tickets);
                tickets.setAirlinerShorter(airlinerService.queryAirliner(itemTickets.getAirliner()));

                tickets.setId(itemTickets.getOrderInfoTicketsId());
                tickets.setTicketNo(itemTickets.getTicketNo());

                item.getOrderTickets().add(tickets);
            });
        });
        return orderList;
    }

    @Override
    public int queryFlightOrderNumber(Long customerId) {
        return flightOrderInfoMapper.queryFlightOrderNumber(customerId);
    }

    /**
     * 行程机票订单
     * */
    @Override
    public JourneyFlightOrderInfoVo journeyFlightOrderInfo(Long orderId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.journeyFlightOrderInfo(orderId);
        List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsMapper.journeyRescheduled(orderId);
        JourneyFlightOrderInfoVo journeyFlightOrderInfoVo = new JourneyFlightOrderInfoVo();
        journeyFlightOrderInfoVo.setOrderId(flightOrderInfo.getOrderId().toString());
        if (flightOrderInfo.getCreateTime() != null){
            journeyFlightOrderInfoVo.setCreateTime(format.format(flightOrderInfo.getCreateTime()));
        }

        journeyFlightOrderInfoVo.setBusinessType(EmHelper.businessType.FLIGHT.getValue());
        journeyFlightOrderInfoVo.setActualPriceTotal(flightOrderInfo.getPayAmount().toString());
        if (flightOrderInfo.getGuestPymtStsId().equals(FlightOrderConstants.waitPay.getValue())){
            journeyFlightOrderInfoVo.setOrderStatusID("未支付");
        }
        else if (flightOrderInfo.getGuestPymtStsId().equals(FlightOrderConstants.payd.getValue())){
            if (flightOrderInfo.getStatus().equals(FlightOrderConstants.noTravel.getValue())){
                journeyFlightOrderInfoVo.setOrderStatusID("未出行");
            }
            else if (flightOrderInfo.getStatus().equals(FlightOrderConstants.refundProgress.getValue())){
                journeyFlightOrderInfoVo.setOrderStatusID("退票中");
            }
            else if (flightOrderInfo.getStatus().equals(FlightOrderConstants.rescheduled.getValue())){
                journeyFlightOrderInfoVo.setOrderStatusID("改期中");
            }
            else if (flightOrderInfo.getStatus().equals(FlightOrderConstants.cancelled.getValue())){
                journeyFlightOrderInfoVo.setOrderStatusID("已取消");
            }
        }
        else if (flightOrderInfo.getGuestPymtStsId().equals(FlightOrderConstants.failPay.getValue())){
            journeyFlightOrderInfoVo.setOrderStatusID("支付失败");
        }

        for (FlightOrderInfoTickets flightOrderInfoTicket : flightOrderInfoTickets) {

            String airliner = airlinerService.queryAirliner(flightOrderInfoTicket.getAirliner());
            if (airliner != null && !airliner.equals("")){
                String logo = filesService.airlineLogo();
                journeyFlightOrderInfoVo.setAirlineLogo(logo + flightOrderInfoTicket.getAirliner() + ".gif");
                journeyFlightOrderInfoVo.setAirliner(airliner);
            }
            else {
                journeyFlightOrderInfoVo.setAirliner(flightOrderInfoTicket.getAirliner());
            }

            journeyFlightOrderInfoVo.setDepartureTerminal(flightOrderInfoTicket.getDepTerm());
            journeyFlightOrderInfoVo.setArrivalTerminal(flightOrderInfoTicket.getArrTerm());
            journeyFlightOrderInfoVo.setFlight(flightOrderInfoTicket.getFlight());
            journeyFlightOrderInfoVo.setDeparture(flightOrderInfoTicket.getDeparture());
            journeyFlightOrderInfoVo.setArrival(flightOrderInfoTicket.getArrival());

            Date departureDate = flightOrderInfoTicket.getDepartureTime();
            Date arrivalDate = flightOrderInfoTicket.getArrivalTime();
            long diff = arrivalDate.getTime() - departureDate.getTime();
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;

            String flightTimes = "";
            if (diffHours == 0) {
                flightTimes = diffMinutes + "分钟";
            } else if (diffMinutes == 0) {
                flightTimes = diffHours + "小时";
            } else if (diffHours != 0 && diffMinutes != 0) {
                flightTimes = diffHours + "小时" + diffMinutes + "分钟";
            }
            journeyFlightOrderInfoVo.setElapsedTime(flightTimes);

            try {
                String departureTime = format.format(flightOrderInfoTicket.getDepartureTime());
                departureTime = departureTime.substring(11, 16);
                journeyFlightOrderInfoVo.setDepartureTime(departureTime);

                String arrivalTime = format.format(flightOrderInfoTicket.getArrivalTime());
                arrivalTime = arrivalTime.substring(11, 16);
                journeyFlightOrderInfoVo.setArrivalTime(arrivalTime);
            } catch (Exception e){
                journeyFlightOrderInfoVo.setDepartureTime(format.format(flightOrderInfoTicket.getDepartureTime()));
                journeyFlightOrderInfoVo.setArrivalTime(format.format(flightOrderInfoTicket.getArrivalTime()));
            }

            break;
        }
        return journeyFlightOrderInfoVo;
    }

    /**
     * 机票订单(远成)
     * */
    @Override
    public List<FlightOrderInfoTickets> selFlightOrderInfoById(Long orderId) {
        List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsMapper.checkTheTicketList(orderId);
        return flightOrderInfoTickets;
    }

    /**
     * 机票订单(远成)
     * */
    @Override
    public List<FlightOrderInfoTickets> selFlightOrderInfo(FlightOrderInfoTickets flightOrderInfoTickets) {
        List<FlightOrderInfoTickets> flightOrderInfoTicketList = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsList(flightOrderInfoTickets);
        return flightOrderInfoTicketList;
    }

    /**
     * 获取支付订单列表
     * */
    @Override
    public List<FlightOrderInfo> payList(String airline, String start, String end) {
        List<FlightOrderInfo> flightOrderInfoList = flightOrderInfoMapper.payList(start, end);
        List<FlightOrderInfo> flightOrderInfoTicketsList = new ArrayList<>();
        for (FlightOrderInfo flightOrderInfo : flightOrderInfoList) {
            List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsMapper.checkTheTicketList(flightOrderInfo.getOrderId());
            if (flightOrderInfoTickets.size() > 0){
                if (flightOrderInfoTickets.get(0).getAirliner().equals(airline)){
                    FlightOrderInfo tmpFlightInfo;
                    tmpFlightInfo = flightOrderInfo;
                    tmpFlightInfo.getInfoTickets().addAll(flightOrderInfoTickets);
                    flightOrderInfoTicketsList.add(tmpFlightInfo);
                }
            }
        }
        return flightOrderInfoTicketsList;
    }

    /**
     * 回填备注
     * */
    @Override
    public int backfillRemarks(Long id, String remark) {
        FlightOrderInfoTickets flightOrderInfoTickets = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsById(id);
        int i = 0;
        if (flightOrderInfoTickets.getOrderId() != null && flightOrderInfoTickets.getOrderId() != 0){
            FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(flightOrderInfoTickets.getOrderId());
            if (flightOrderInfo != null && flightOrderInfo.getGuestMemo() != null){
                remark = flightOrderInfo.getGuestMemo() +  "," + remark;
            }
            i = flightOrderInfoMapper.backfillRemarks(flightOrderInfoTickets.getOrderId(), remark);
        }
        return i;
    }

    /**
     * 订单号获取机票订单信息（远程）
     * */
    @Override
    public FlightOrderInfo order(Long orderId) {
        FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.order(orderId);
        return flightOrderInfo;
    }

    @Override
    public List<FlightOrderList> orderListThings()
    {
        return flightOrderInfoMapper.getOrderListThings();
    }

}
